import json

import genson
from jsonschema import validate, ValidationError, SchemaError

from utils.log_setting import logger

# 生成schema格式
def build_schema():
    builder = genson.SchemaBuilder
    builder.add_object({"a":"123","b":23,"c":0.2,"d":None})
    json.dump(builder.to_schema(),open("schema.json","w",encoding='utf-8'))


def schema_validate(obj, schema):
    '''
    :param obj:要校验的对象
    :param schema: schema个格式
    :return: 校验成功或失败
    '''
    try:
        # 进行jsonshcema校验尝试
        validate(instance=obj, schema=schema)
    except ValidationError as e:
        path = "--->".join(i for i in e.path)
        logger.error(f"验证出错，错误的位置为{path},错误信息为{e.message}")
        return False
    except SchemaError as e:
        logger.error(f"验证出错，错误信息为{e.message}")
        return False
    else:
        logger.info("验证成功")
        return True
